const app = getApp();
const api = require('../../utils/api');
const util = require('../../utils/util.js');
const constant = require('../../utils/constant');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //获取全局变量 导航栏的高度statusBarHeight
    statusBarHeight: app.globalData.statusBarHeight,
    // 胶囊
    jiaonang: app.globalData.jiaonang, 
    navigationHeight: app.globalData.navigationHeight,
    BASEURLWWW:constant.BASEURLWWW,
    // 商品
    goods: {},
    // 是否是退货操作
    isRefunds: false,
    // 申请数量
    apply_num: 1,
    // 弹窗
    popupShow: false,
    popup:{
      mode: '',
      title: '',
      list: []
    },
    chooseListId: null,
    // form表单数据
    formData:{
      type: '',
      status: '',
      because: '',
      reason: '',
      typeId: null
    },
    // 退款金额
    refundAmount: 0,
    // 选择图片
    tempFilePaths: []
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.goods){
      let goods = JSON.parse(options.goods);
      goods.order_goods.forEach(item => {
        item.apply_num = 1;
      })
      this.setData({
        goods
      })
      console.log(goods);
      this.refundAmount();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 返回上一级
  back:function(){
    wx.navigateBack({
      delta: 1,
    })
  },
  // 背景不滚动
  dontMove: function(){
    return;
  },

  // 显示弹窗
  handlePopup:function(e){
    let mode = e.currentTarget.dataset.mode;
    let popup = {};
    popup.mode = mode;
    if(mode == 'type'){
      popup.title = '请选择申请类型';
      popup.list = [
        {id:1,content: '我需要退货退款',selected: true},
        {id:2,content: '我要退款(无需退货)',selected: false}
      ]
    }
    if(mode == 'status'){
      popup.title = '请选择收货状态'
      popup.list = [
        {id:1,content: '未收到货',selected: false},
        {id:2,content: '已收到货',selected: false}
      ]
    }
    if(mode == 'because'){
      popup.title = '请选择申请原因'
      popup.list = [
        {id:1,content: '多拍、错拍、不想要',selected: false},
        {id:2,content: '重量/数量/大小等描述不符',selected: false},
        {id:3,content: '图片/品种/口味/标签/等描述不符',selected: false},
        {id:4,content: '包装/商品破损',selected: false},
        {id:5,content: '少件/漏发',selected: false},
        {id:6,content: '商品变质/发霉/有异物',selected: false},
        {id:7,content: '生产日期/保质期与商品描述不符',selected: false},
        {id:8,content: '质量问题',selected: false},
        {id:9,content: '商家发错货',selected: false},
        {id:10,content: '假冒产品',selected: false},
        {id:11,content: '其他',selected: false}
      ]
    }
    this.setData({
      popupShow: true,
      popup
    })
    console.log(e.currentTarget.dataset.mode);
  },
  // 申请数量+
  plus: function(e){
    let order_goods_id = e.currentTarget.dataset.ordergoodsid;
    let goods = this.data.goods;
    goods.order_goods.forEach(item => {
      if(item.order_goods_id == order_goods_id){
        if(item.apply_num >= item.goods_num){
          wx.showToast({
            title: '申请数量不能超过购买商品数量',
            icon: 'none'
          })
        }else{
          item.apply_num += 1;
          this.setData({
            goods
          })
        }
      }
    })
    this.refundAmount();
  },
  // 申请数量-
  minus: function(e){
    let order_goods_id = e.currentTarget.dataset.ordergoodsid;
    let goods = this.data.goods;
    goods.order_goods.forEach(item => {
      if(item.order_goods_id == order_goods_id){
        if(item.apply_num <= 1){
          item.apply_num = 1;
        }else{
          item.apply_num -= 1;
        }
      }
    })
    this.setData({
      goods
    })
    this.refundAmount();
  },
  // 退款金额
  refundAmount:function(){
    let goods = this.data.goods;
    let amount = 0;
    goods.order_goods.forEach(item => {
      amount += item.apply_num * parseFloat(item.goods_price);
    })
    this.setData({
      refundAmount: amount
    })
  },
  // 去退货
  handleRefunds:function(){
    this.setData({
      isRefunds: true
    })
  },
  // 弹窗列表选择
  listChoose:function(e){
    this.setData({
      chooseListId: e.currentTarget.dataset.id,
    })
  },
  // 关闭弹窗
  closePopup: function(){
    let popup = this.data.popup;
    let newFormData = this.data.formData;
    popup.list.forEach(item => {
      if(this.data.chooseListId == item.id){
        if(popup.mode == 'type'){
          newFormData.type = item.content;
          newFormData.typeId = item.id
        }
        if(popup.mode == 'status'){
          newFormData.status = item.content;
        }
        if(popup.mode == 'because'){
          newFormData.because = item.content;
        }
      }
    })
    this.setData({
      popupShow: false,
      formData: newFormData
    })
  },
  // 申请说明
  textareaInput:function(e){
    let reason = util.trimStr(e.detail.value)
    this.setData({
      'formData.reason':reason
    })
  },
  // 上传图片
  upload:function(){
    let that = this;
    let tempFilePaths = this.data.tempFilePaths;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success (res) {
        // tempFilePath可以作为img标签的src属性显示图片
        console.log(tempFilePaths)
        wx.uploadFile({
          url: 'https://api.changlejiuhang.com/myfile/wechat', //仅为示例，非真实的接口地址
          filePath: res.tempFilePaths[0],
          name: 'file',
          formData: {
            'user': 'test'
          },
          success (res){
            // const data = res.data
            //do something
            let jsonObj = JSON.parse(res.data)
            console.log(jsonObj);
            if(jsonObj.code == 0){
              tempFilePaths.push(jsonObj.data);
              that.setData({
                tempFilePaths
              })
            }
          }
        })
        
        
      }
    })
  },
  // 移除图片
  removeImg:function(e){
    let index = e.currentTarget.dataset.index;
    let tempFilePaths = this.data.tempFilePaths;
    tempFilePaths.splice(index,1);
    this.setData({
      tempFilePaths
    })
  },
  // 提交申请
  refundsSubmit:function(){
    let requestData = {
      order_goods: []
    };
    let formData = this.data.formData;
    let goods = this.data.goods;
    let tempFilePaths = this.data.tempFilePaths;
    // 申请类型必填
    if(formData.typeId == null){
      wx.showToast({
        title: '请选择申请类型',
        icon: 'none'
      })
      return false;
    }
    if(formData.typeId == 2 && formData.status == ""){
      wx.showToast({
        title: '请选择收货状态',
        icon: 'none'
      })
      return false;
    }
    if(formData.because == ""){
      wx.showToast({
        title: '请选择申请原因',
        icon: 'none'
      })
      return false;
    }
    if(formData.reason == ""){
      wx.showToast({
        title: '请填写申请说明',
        icon: 'none'
      })
      return false;
    }

    // 收集表单数据
    requestData.refund_type = formData.type; // 申请类型
    requestData.receiving_status = formData.status; // 收货状态
    requestData.reason = formData.because; // 申请原因
    requestData.buyer_remark = formData.reason // 申请说明
    // 收集图片 refound_pic:[]
    requestData.refound_pic = tempFilePaths;
    // 收集订单和商品数据
    requestData.order_id = goods.order_id;
    goods.order_goods.forEach(item => {
        requestData.order_goods.push({order_goods_id:item.order_goods_id,qty:item.apply_num});
    })
    api.applyRefound(requestData).then(res => {
      console.log(res);
      if(res.code == 0){
        wx.reLaunch({
          url: '/pages/afterSales/afterSales?current=1',
        })
      }else{
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  }
})